package com.haoshui.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haoshui.domain.entity.RoleMenu;
import com.haoshui.mapper.RoleMenuMapper;
import com.haoshui.service.RoleMenuService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色和菜单关联表(RoleMenu)表服务实现类
 *
 * @author makejava
 * @since 2022-09-30 20:59:55
 */
@Service("roleMenuService")
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    @Override
    public List<Long> selectMenusByRoleId( Long roleId) {
        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId, roleId);
        List<RoleMenu> roleMenuList = list(queryWrapper);
        List<Long> collect = roleMenuList.stream()
                .map(meun -> meun.getMenuId())
                .collect(Collectors.toList());
        return collect;
    }

    @Override
    public boolean addRoleMenu(Long id, List<Long> menuIds) {
        System.out.println(id);
        List<RoleMenu> collect = menuIds.stream()
                .map(menuId -> new RoleMenu(id, menuId))
                .collect(Collectors.toList());

        boolean b = saveBatch(collect);

        return b;
    }

    @Override
    public boolean updateRoleMenu(Long id, List<Long> menuIds) {
        //转化成RoleMenu
        List<RoleMenu> collect = menuIds.stream()
                .map(o -> new RoleMenu(id, o))
                .collect(Collectors.toList());

        //更新
        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId, id);
        if(list(queryWrapper).size()>0){
            remove(queryWrapper);
        }

        if(collect.size()>0){
            boolean b = saveBatch(collect);
            return b;
        }else{
            return true;
        }

    }

}
